var db = require('../config/mongo_database');
var redisClient = require('../config/redis_database').redisClient;
var tokenManager = require('../config/token_manager');
var sms = require('../route/sms');
var request = require('request');

var SETVAL = 1.618;

exports.index = function(req, res){
	request('http://web.juhe.cn:8080/finance/gold/shgold?v=&key=03d9124bc4287ec2bc732c55679ad705', function (error, response, body) {
		if (!error && response.statusCode == 200) {
	  		resultGold = JSON.parse(body);
	  		resultGold = resultGold.result[0][4];
	  		res.json(resultGold)
		}
	});
}

exports.getGold =  function(req, res){
	//获取黄金价格 风险区最高价-最低价*0.618 +最低价，(最高价-（最高价+最低价）/2)**0.618 + （最高价+最低价）/2)
	// 收盘价预估 （最高-最低）*0.618+最低价
	request('http://web.juhe.cn:8080/finance/gold/shgold?v=&key=03d9124bc4287ec2bc732c55679ad705', function (error, response, body) {
		if (!error && response.statusCode == 200) {
	  		resultGold = JSON.parse(body);
	  		resultGold = resultGold.result[0][4];
	  		console.log(resultGold)
	  		db.goldModel.find({'flag':'1'}, function(err, data){
	  			updateStatus(2, data, resultGold)
				if(Number(resultGold.latestpri) >= (data.value+SETVAL)){
					if(data.status == '0'){
						sms.send('13641892349', 4, [new Date(), resultGold.latestpri])
						updateStatus(1, data, resultGold)
					}
				}else if(Math.abs(Number(resultGold.latestpri)-data.value) <= SETVAL){
					if(data.status == '0'){
						sms.send('13641892349', 4, [new Date(), resultGold.latestpri])
						updateStatus(1, data, resultGold)
					}
				}
			})
		}
	});
}

exports.detail =  function(req, res){
	var result = {};
	db.goldModel.find({'flag':'1'}, function(err, data){
		result.low = (data.high - data.low)*0.618 +  data.low;
		var aveg = ((data.high + data.low)/2).toFixed(2)
		result.high = (data.high - aveg)*0.618 + aveg;
	})
}




function updateStatus(type, data, gold){
	if(type==1)
		db.goldModel.update({'flag':'1'}, {$set:{status:'1'}}, function(err){})
	else{
		if(Number(gold.maxpri) > data.high)
			db.goldModel.update({'flag':'1'}, {$set:{high:Number(gold.maxpri)}}, function(err){})
		if(Number(gold.minpri) > data.low)
			db.goldModel.update({'flag':'1'}, {$set:{low:Number(gold.minpri)}}, function(err){})
	}
}